package cn.lcj.pet.service.impl;

import cn.lcj.basic.exception.BusinessException;
import cn.lcj.basic.service.impl.BaseServiceImpl;
import cn.lcj.basic.utils.*;
import cn.lcj.order.domain.OrderPetAcquisition;
import cn.lcj.order.mapper.OrderPetAcquisitionMapper;
import cn.lcj.org.domain.Employee;
import cn.lcj.org.domain.Shop;
import cn.lcj.org.mapper.EmployeeMapper;
import cn.lcj.org.mapper.ShopMapper;
import cn.lcj.pet.domain.SearchMasterMsg;
import cn.lcj.pet.domain.SearchMasterMsgAuditLog;
import cn.lcj.pet.dto.MsgDto;
import cn.lcj.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.lcj.pet.mapper.SearchMasterMsgMapper;
import cn.lcj.pet.query.SearchMasterMsgQuery;
import cn.lcj.pet.service.IBaiduAiAuditService;
import cn.lcj.pet.service.ISearchMasterMsgService;
import cn.lcj.user.domain.Logininfo;
import cn.lcj.user.domain.User;
import cn.lcj.user.mapper.UserMapper;
import org.apache.xmlbeans.impl.xb.ltgfmt.Code;
import org.junit.jupiter.api.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg msg, HttpServletRequest request) {

        //        id        -   自增长
        //        name      -   来自页面
        //        age       -   来自页面
        //        gender    -   来自页面
        //        coat_color-   来自页面
        //        resources -   来自页面
        //        pet_type  -   来自页面
        //        price     -   来自页面
        //        address   -   来自页面
        //        state     -   来自实体默认值 //0表示待审核,-1驳回， 1表示已审核待处理，2表示处理成功
        //        title     -   来自页面
        //        user_id   -   谁发布的寻主消息 = 用户 = 登录了才能发布
        //        shop_id   -   获取最近的门店的id

        //.添加到数据库
        Logininfo logininfo = LogininfoContext.getLogininfo(request);
        User user = userMapper.loadByLoginfo(logininfo.getId());
        msg.setUserId(user.getId());
        searchMasterMsgMapper.save(msg);//自增id
        //2.百度ai只能审核
        Boolean boo1 = baiduAiAuditService.imageAudit(msg.getResources());
        Boolean boo2 = baiduAiAuditService.textAudit(msg.getName() + msg.getAddress());
        if (boo1 && boo2) {//审核通过
            msg.setState(1);
            //添加审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(1);
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);
            //获取里用户最近的商店
            Point point = DistanceUtils.getPoint(msg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            if (nearestShop != null) {//找到最近的店铺
                msg.setShopId(nearestShop.getId());
                //发消息给店铺
                //SmsUtils.sendSms(nearestShop.getTel(),"你有新订单，亲尽快去"+user.getPhone()+"联系");
                System.out.println("你有新订单，亲尽快去" + user.getPhone() + "联系");
            } else {
                msg.setState(3);
                System.out.println("抱歉,你附近暂时没有店面,请换个位置试试");
            }
            searchMasterMsgMapper.update(msg);
            //return给前端
            return new AjaxResult();
        } else {//审核不通过
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(msg.getId());
            log.setState(0);
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);
            //发信息-用户
            System.out.println("寻主信息发布失败，请修改之后再试");
            searchMasterMsgMapper.del(msg.getId());
            //返回给前端
            return new AjaxResult(false, "审核未通过，请修改之后再试");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //用户查询自己的寻主消息，设值userId
        Logininfo logininfo = LogininfoContext.getLogininfo(request);
        User user = userMapper.loadByLoginfo(logininfo.getId());
        query.setUserId(user.getId());
        return  super.queryPage(query);


    }

    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);
        Logininfo logininfo = LogininfoContext.getLogininfo(request);
        Employee employee=employeeMapper.loadByLoginfo(logininfo.getId());
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
      //查寻寻主池的消息
       query.setState(3);
    return  super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);
        //区分平台管理员或店铺管理员
        Logininfo logininfo = LogininfoContext.getLogininfo(request);
        Employee employee=employeeMapper.loadByLoginfo(logininfo.getId());
        if(employee.getShop_id() != null){//店铺管理员
            query.setShopId(employee.getShop_id());
        }

        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(MsgDto msgDto) {
        //平台将寻主消息分给你这个店铺
        //店铺收到消息后派人去接收
        //判断订单是否存在-说明人已经去处理了，不该重复结单
        //1.判断订单是否存在
        //存在
        SearchMasterMsg order=searchMasterMsgMapper.loadById(msgDto.getMsgId());
        if(order!=null&&order.getState()==0){ //有订单，且在处理
            throw new BusinessException("你的订单正在处理，请不要重复提交");
        }
        //不存在
        //生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.loadById(msgDto.getMsgId());
        OrderPetAcquisition newOrder=createOrder(msg,msgDto);
        orderPetAcquisitionMapper.save(newOrder);
        //告诉别人在规定的时间内去接收宠物，发短信 2分钟
       /* Employee employee = employeeMapper.loadById(msgDto.getHandler());
        SmsUtils.sendSms(employee.getPhone("你有新订请在2天内去"+msg.getAddress()+"接回"));
        */
        System.out.println("你有新订请在2天内去"+msg.getAddress()+"接回");
    }
    private  OrderPetAcquisition createOrder(SearchMasterMsg msg,MsgDto msgDto){
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(msg.getNote());

        //3天后没领取就去取消  定时器
        order.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        order.setPrice(msg.getPrice());
        //支付类型 - 确认订单才设置
        //宠物id - 确认订单，接回宠物再设置
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(msgDto.getHandler());
        order.setSearchMasterMsgId(msgDto.getMsgId());
        return order;
    }
}
